package com.admin.controller;


import com.admin.entity.Admin;
import com.admin.excelList.TerminalList;
import com.admin.excelList.TerminalListkey;
import com.admin.service.IAdminService;
import com.admin.service.ITerminalKeyService;
import com.admin.service.ITerminalService;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bean.ResponseBean;
import com.excel.ExcelUtil;
import com.excel.Terminal_key_Info;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author marisheng
 * @since 2019-11-21
 */
@RestController
@RequestMapping("/admin/terminal-key")
public class TerminalKeyController {

    @Autowired
    private ITerminalKeyService terminalKeyService;

    @Autowired
    private ITerminalService terminalService;

    @Autowired
    private IAdminService adminService;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private HttpServletRequest request;

    /**
     * 查看该终端下已过期和使用中的密钥信息  和   根据开始时间和结束时间进行条件模糊查询详情
     * @param page
     * @param limit
     * @param map  终端编号  开始时间  结束时间
     * @return
     */
    @RequestMapping("/findByTimeORFindALL")
    public ResponseBean findByTimeORFindALL(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map map){
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        IPage ipage = terminalKeyService.findByTimeORFindAll(page,limit,map);
        return new ResponseBean(0,ipage.getTotal(),ipage.getRecords());
    }

    /**
     * 通过站点编号 查询站点下面所有未使用的密钥（若该终端正在使用密钥 直接return）
     * @param station_id 站点编号
     * @return
     */
    @GetMapping("/selectPassword")
    public ResponseBean selectTerminalPasswordById(@RequestParam(defaultValue = "0") Integer station_id,@RequestParam Integer terminal_id){
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        if(station_id==0) {
            List<Map> list = terminalKeyService.selectTerminalPasswordById(station_id);
            return new ResponseBean(0,"成功",list);
        }
        String miYao = terminalKeyService.checkTerminalPassword(terminal_id);

        if(miYao!=null && miYao.length()!=0){
            return new ResponseBean(200,"已授权",null);
        }
        List<Map> list = terminalKeyService.selectTerminalPasswordById(station_id);
        return new ResponseBean(0,"成功",list);

    }
    /**
     * 根据站点编号来查询站点下的所有密钥  并做分页根据搜索条件
     * @param map   查询条件
     * @return
     */
    @GetMapping("/findByStationIdQueryPassword")
    public ResponseBean findByStationIdQueryPassword(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "10") int limit,@RequestParam Map<String,String> map){
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        IPage byStationIdQueryPassword = terminalKeyService.findByStationIdQueryPassword(page, limit, map);
        return new ResponseBean(0,byStationIdQueryPassword.getTotal(),byStationIdQueryPassword.getRecords());
    }

    /**
     * 根据站点查终端
     * @return
     */
    @GetMapping("/findByStationIdQueryTerminal")
    public ResponseBean findByStationIdQueryTerminal(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "10") int limit,@RequestParam Map map){
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        IPage byStationIdQueryTerminal = terminalKeyService.findByStationIdQueryTerminal(page, limit, map);
        return  new ResponseBean(0,byStationIdQueryTerminal.getTotal(),byStationIdQueryTerminal.getRecords());
    }

    /**
     * 密钥授权接口 分标准型（一天）和钟点型（自己设置结束时间），
     * 上面由前端来判断 最后传入当前时间和结束时间即可
     * 1.把时间更新在终端密钥表中 并修改状态（后期还有一个接口：结束时间到了 修改状态为过期*）
     * 2.密钥值更新在终端表中（通过终端id）
     */
    @GetMapping("/usePasswordKey")
    public ResponseBean setPasswordKey(Integer terminal_key_id,Integer terminal_id,String terminal_key_value,String terminal_key_begin_time,String terminal_key_end_time,String terminal_room,String terminal_bh,String admin_id){
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        int updateId = terminalService.selectAdminIdByStationBh(terminal_bh);
        //200成功 500失败
        int i = adminService.selectQuanxian(updateId, admin_id);
        if(i==500){
            return new ResponseBean(403,"权限不足",null);
        }
        int n=  terminalKeyService.terminalShouQuan(terminal_key_id,terminal_id,terminal_key_value,terminal_key_begin_time,terminal_key_end_time,terminal_room);
        return ResponseBean.vo(n,0);
    }

    @GetMapping("/usePasswordKeyRoomType")
    public ResponseBean usePasswordKeyRoomType(Integer terminal_key_id,Integer terminal_id,String terminal_key_value,String terminal_key_begin_time,String terminal_key_end_time,Integer terminal_key_room,String terminal_key_room_type){
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        int n=  terminalKeyService.terminalShouQuanRoom(terminal_key_id,terminal_id,terminal_key_value,terminal_key_begin_time,terminal_key_end_time,terminal_key_room,terminal_key_room_type);
        return ResponseBean.vo(n,0);
    }

    /**
     * 查询所有密钥分页显示
     * @param map
     * @return
     */
    @GetMapping("/selectTerminalKeys")
    public ResponseBean selectTerminalKeys(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map map) {
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        IPage iPage = terminalKeyService.selectTerminalKeys(page, limit, map);
        return new ResponseBean(0, iPage.getTotal(), iPage.getRecords());
    }
    /**
     * 导出Excel
     * @param map
     * @return
     */
    @GetMapping("/selectTerminalKeysExcel")
    public void selectTerminalKeysExcel(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map map) throws IOException {
        List<TerminalListkey> list = terminalKeyService.selectTerminalKeysExcel();
        ServletOutputStream out = response.getOutputStream();
        ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
        String fileName = "Terminal_Excel";
        Sheet sheet = new Sheet(1, 0, TerminalList.class);
        //设置自适应宽度
        sheet.setAutoWidth(Boolean.TRUE);
        // 第一个 sheet 名称
        sheet.setSheetName("第一个sheet");
        writer.write(list, sheet);
        //通知浏览器以附件的形式下载处理，设置返回头要注意文件名有中文
        response.setHeader("Content-disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) + ".xlsx");
        writer.finish();
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        out.flush();
    }
    /**
     * 查询站点下的所有秘钥
     * @return
     */
    @RequestMapping(value = "/query/terminalKey",method = RequestMethod.GET)
    public ResponseBean queryTerminalKey(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map map){
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        IPage iPage = terminalKeyService.findByStationIdQueryPassword(page, limit, map);
        return new ResponseBean(0, iPage.getTotal(), iPage.getRecords());
    }

    /**
     * 查询站点下的所有秘钥 导出Excel
     * @return
     */
    @RequestMapping(value = "/query/terminalKeyExcel",method = RequestMethod.GET)
    public ResponseBean queryTerminalKeyExcel(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map map){
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        IPage iPage = terminalKeyService.findByStationIdQueryPasswordExcel(page, limit, map);

        List<Terminal_key_Info> list = iPage.getRecords();
        String fileName = "Termain_Key Excel";
        String sheetName = "sheet";

        ExcelUtil.writeExcelWithSheets(response, list, fileName, sheetName, new Terminal_key_Info())
                .finish();

        return new ResponseBean(0, iPage.getTotal(), iPage.getRecords());
    }


}
